package com.liuym.student.controller;

import com.liuym.common.constants.GradeResponse;
import com.liuym.common.constants.ResponseCodeConstants;
import com.liuym.common.exception.StudentException;
import com.liuym.student.repository.model.bo.StudentBO;
import com.liuym.student.repository.model.vo.StudentVO;
import com.liuym.student.service.StudentService;
import com.vip.vjtools.vjkit.mapper.BeanMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @author Liuym
 * @date 2019/4/11 14:21
 * @describe：
 */
@RestController
@RequestMapping("/studentReset")
public class StudentResetPasswordController {
    private static Logger logger = LoggerFactory.getLogger(StudentResetPasswordController.class);

    @Autowired
    private StudentService studentService;

    @PutMapping("/resetPassword")
    public GradeResponse resetPassword(@RequestParam Map<String, Object> params) {
        StudentVO student = null;
        StudentBO studentBO = null;
        try {
            studentBO = studentService.getStudentByNumber(Long.parseLong(params.get("studentNumber").toString()));
            if (studentBO != null) {
                if (studentBO.getName().equals(String.valueOf(params.get("name")))) {
                    student = BeanMapper.map(studentBO, StudentVO.class);
                }
            }
        } catch (StudentException e) {
            if (e instanceof StudentException) {
                logger.warn("error", e);
                return GradeResponse.fail(((StudentException) e).getCode(), ((StudentException) e).getMsg());
            }
        }
        if (student != null) {
            try {
                studentService.resetPassword(studentBO);
            } catch (StudentException e) {
                if (e instanceof StudentException) {
                    logger.warn("error", e);
                    return GradeResponse.fail(((StudentException) e).getCode(), ((StudentException) e).getMsg());
                }
            }
            return GradeResponse.success("操作成功!", "");
        } else {
            return GradeResponse.fail(ResponseCodeConstants.RESETPASSWORD_FAIL_CODE, ResponseCodeConstants.RESETPASSWORD_FAIL_MSG);
        }
    }
}
